<!-- 曲线分析查询 -->
<template>
	<div class="dashboard-container">
		<div class="form-container">
			<el-form :model="form" label-width="auto" :inline="true">
				<el-form-item :label="$t('message.lineAnalyseQuery.pageDeviceType')">
					<el-select
						v-model="form.deviceType"
						:placeholder="$t('message.form.pageSelectHolder')"
						style="width: 200px"
						class="custom-select"
						size="default"
					>
						<el-option v-for="item in deviceTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
					</el-select>
				</el-form-item>

				<el-form-item :label="$t('message.lineAnalyseQuery.pageSubstationChange')">
					<el-select
						v-model="form.substation"
						:placeholder="$t('message.form.pageSelectHolder')"
						style="width: 200px"
						class="custom-select"
						size="default"
					>
						<el-option v-for="item in substationOptions" :key="item.value" :label="item.label" :value="item.value" />
					</el-select>
				</el-form-item>

				<el-form-item :label="$t('message.lineAnalyseQuery.pageDeviceChange')">
					<el-select
						v-model="form.device"
						:placeholder="$t('message.form.pageSelectHolder')"
						style="width: 200px"
						class="custom-select"
						size="default"
					>
						<el-option v-for="item in deviceOptions" :key="item.value" :label="item.label" :value="item.value" />
					</el-select>
				</el-form-item>

				<el-form-item :label="$t('message.lineAnalyseQuery.pageDataClass')">
					<el-select
						v-model="form.dataCategory"
						:placeholder="$t('message.form.pageSelectHolder')"
						style="width: 200px"
						class="custom-select"
						size="default"
					>
						<el-option v-for="item in categoryOptions" :key="item.value" :label="item.label" :value="item.value" />
					</el-select>
				</el-form-item>

				<el-form-item :label="$t('message.lineAnalyseQuery.pagePointClass')">
					<el-select
						v-model="form.measurementCategory"
						:placeholder="$t('message.form.pageSelectHolder')"
						style="width: 200px"
						class="custom-select"
						size="default"
					>
						<el-option v-for="item in measureOptions" :key="item.value" :label="item.label" :value="item.value" />
					</el-select>
				</el-form-item>

				<el-form-item :label="$t('message.lineAnalyseQuery.pageDateChange')">
					<el-date-picker
						size="default"
						v-model="form.dateRange"
						type="daterange"
						:range-separator="$t('message.lineAnalyseQuery.pageTo')"
						:start-placeholder="$t('message.lineAnalyseQuery.pageStartTime')"
						:end-placeholder="$t('message.lineAnalyseQuery.pageEndTime')"
						class="custom-date-dateRange-picker"
						:picker-options="pickerOptions"
					/>
				</el-form-item>

				<el-form-item :label="$t('message.lineAnalyseQuery.pagePointList')">
					<el-select
						v-model="form.measurementPoints"
						:placeholder="$t('message.form.pageSelectHolder')"
						style="width: 200px"
						class="custom-select"
						size="default"
					>
						<el-option v-for="item in pointOptions" :key="item.value" :label="item.label" :value="item.value" />
					</el-select>
				</el-form-item>

				<el-form-item>
					<el-button size="default" type="primary" @click="handleSearch">{{ $t('message.form.pageQuery') }}</el-button>
					<el-button size="default" type="warning" @click="handleExport">{{ $t('message.form.pageExport') }}</el-button>
					<el-button size="default" type="success" @click="handlePrint">{{ $t('message.form.pagePrint') }}</el-button>
				</el-form-item>
			</el-form>
		</div>

		<div class="chart-container">
			<div ref="chartRef" style="width: 100%; height: 500px"></div>
		</div>

		<PrintComponent ref="printComponentRef"> </PrintComponent>
	</div>
</template>

<script lang="ts">
import * as echarts from 'echarts';
import PrintComponent from '../../components/print/index.vue';
import { defineComponent, reactive, toRefs, onMounted, onBeforeUnmount, ref } from 'vue';

export default defineComponent({
	name: 'lineAnalyseQuery',

	components: { PrintComponent },

	setup() {
		const chartRef = ref<HTMLDivElement | null>(null);
		let chartInstance: echarts.ECharts | null = null;
		let dataTimer: ReturnType<typeof setInterval> | null = null; // 修复：类型更精确

		const isFullscreen = ref(false); // 全屏状态标志

		// 全屏切换函数
		const toggleFullscreen = () => {
			if (!chartRef.value) return;

			if (!isFullscreen.value) {
				chartRef.value
					.requestFullscreen()
					.then(() => {
						isFullscreen.value = true;
						updateChartOptions(); // 更新全屏按钮状态
					})
					.catch((err) => {
						console.error('全屏失败:', err);
					});
			} else {
				document.exitFullscreen();
			}
		};

		const state = reactive({
			form: {
				deviceType: '',
				substation: '',
				device: '', // 确保字段名唯一且语义明确
				dataCategory: '',
				measurementCategory: '',
				dateRange: [new Date(), new Date()],
				measurementPoints: '',
			},
			deviceTypeOptions: [
				{ value: '1', label: '设备类型1' },
				{ value: '2', label: '设备类型2' },
			],
			deviceOptions: [
				{ value: '1', label: '设备类型1' },
				{ value: '2', label: '设备类型2' },
			],
			substationOptions: [
				{ value: '1', label: '子站1' },
				{ value: '2', label: '子站2' },
			],
			categoryOptions: [
				{ value: '1', label: '电压' },
				{ value: '2', label: '电流' },
			],
			measureOptions: [
				{ value: '1', label: '测点分类1' },
				{ value: '2', label: '测点分类2' },
			],
			pointOptions: [
				{ value: '1', label: '测点1' },
				{ value: '2', label: '测点2' },
			],
			pickerOptions: {
				disabledDate(time: Date) {
					return time.getTime() > Date.now();
				},
			},
			chartOption: {
				tooltip: {
					trigger: 'axis',
					formatter: (params: any) => {
						const date = params[0].axisValue;
						const value = params[0].data;
						return `${date}<br/>数值: ${value}`;
					},
				},
				grid: {
					left: '3%',
					right: '4%',
					bottom: '5%',
					containLabel: true,
				},
				toolbox: {
					feature: {
						saveAsImage: {},
						restore: {},
						myFullscreen: {
							// 自定义全屏按钮
							show: true,
							title: isFullscreen.value ? '退出全屏' : '全屏',
							icon: isFullscreen.value
								? 'path://M432.45,595.444c0,2.177-4.661,6.82-11.305,6.82c-6.475,0-11.306-4.567-11.306-6.82s4.852-6.812,11.306-6.812C427.841,588.632,432.452,593.191,432.45,595.444L432.45,595.444z M421.155,589.876c-3.009,0-5.448,2.495-5.448,5.572s2.439,5.572,5.448,5.572c3.01,0,5.449-2.495,5.449-5.572C426.604,592.371,424.165,589.876,421.155,589.876L421.155,589.876z M421.146,591.891c-1.916,0-3.47,1.589-3.47,3.549c0,1.959,1.554,3.548,3.47,3.548s3.469-1.589,3.469-3.548C424.614,593.479,423.062,591.891,421.146,591.891L421.146,591.891zM421.146,591.891'
								: 'path://M432.45,595.444c0,2.177-4.661,6.82-11.305,6.82c-6.475,0-11.306-4.567-11.306-6.82s4.852-6.812,11.306-6.812C427.841,588.632,432.452,593.191,432.45,595.444L432.45,595.444z M421.155,589.876c-3.009,0-5.448,2.495-5.448,5.572s2.439,5.572,5.448,5.572c3.01,0,5.449-2.495,5.449-5.572C426.604,592.371,424.165,589.876,421.155,589.876L421.155,589.876z M421.146,591.891c-1.916,0-3.47,1.589-3.47,3.549c0,1.959,1.554,3.548,3.47,3.548s3.469-1.589,3.469-3.548C424.614,593.479,423.062,591.891,421.146,591.891L421.146,591.891zM421.146,591.891',
							onclick: toggleFullscreen,
						},
					},
				},
				dataZoom: [
					// 区域缩放配置
					{
						type: 'slider',
						xAxisIndex: 0,
						start: 0,
						end: 100,
						bottom: '5%', // 调整位置
						height: 20,
						handleSize: '80%',
						handleStyle: {
							color: '#5fcffa',
							shadowBlur: 3,
							shadowColor: 'rgba(0, 0, 0, 0.6)',
							shadowOffsetX: 2,
							shadowOffsetY: 2,
						},
						fillerColor: 'rgba(95, 207, 250, 0.2)',
						borderColor: '#2d4a7a',
					},
					{
						type: 'inside',
						xAxisIndex: 0,
						zoomOnMouseWheel: true,
						moveOnMouseMove: true,
					},
				],
				xAxis: {
					type: 'category',
					boundaryGap: false,
					data: generateTimeAxis(),
					axisLabel: {
						color: '#fff', // x轴标签颜色
						formatter: (value: string) => {
							return value.split(' ')[1]; // 只显示时间部分
						},
					},
					axisLine: {
						// 可选：y轴轴线样式
						lineStyle: {
							color: '#5fcffa', // y轴轴线颜色
						},
					},
				},
				yAxis: {
					type: 'value',
					name: '数值',
					splitLine: {
						// 新增配置，修改横轴线样式
						lineStyle: {
							color: '#2d4a7a', // 横轴线颜色（与您主题一致的浅蓝色）
							type: 'dashed', // 可选：虚线样式（solid为实线）
							width: 1, // 线宽
							opacity: 0.6, // 透明度
						},
					},
					axisLine: {
						// 可选：y轴轴线样式
						lineStyle: {
							color: '#5fcffa', // y轴轴线颜色
						},
					},
					axisLabel: {
						// 可选：y轴标签样式
						color: '#fff', // 标签颜色
					},
				},
				series: [
					{
						name: '数据值',
						type: 'line',
						data: [] as number[],
						smooth: true,
						areaStyle: {
							opacity: 0.3,
							color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
								// 可选：渐变区域颜色
								{
									offset: 0,
									color: 'rgba(95, 207, 250, 0.5)',
								},
								{
									offset: 1,
									color: 'rgba(95, 207, 250, 0.1)',
								},
							]),
						},
						lineStyle: {
							// 可选：线条样式
							color: '#5fcffa',
							width: 2,
						},
						itemStyle: {
							// 可选：数据点样式
							color: '#5fcffa',
						},
						markLine: {
							silent: true,
							data: [
								{
									type: 'average',
									name: '平均值',
									lineStyle: {
										// 可选：平均值线样式
										color: '#ffa726',
										width: 2,
										type: 'solid',
									},
									label: {
										// 可选：平均值标签样式
										color: '#ffa726',
									},
								},
							],
						},
					},
				],
				// 可选：全局背景色
				// backgroundColor: '#0a1a32',
			}, // 同时使用 ECharts 官方类型进行整体标注
		});

		// 生成00:00到16:30的时间轴（每30分钟一个点）
		function generateTimeAxis() {
			const timePoints = [];
			for (let hour = 0; hour <= 16; hour++) {
				for (let minute = 0; minute < 60; minute += 30) {
					if (hour === 16 && minute > 30) break;
					const timeStr = `${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`;
					timePoints.push(`${getCurrentDate()} ${timeStr}`);
				}
			}
			return timePoints;
		}

		// 获取当前日期（YYYY-MM-DD格式）
		function getCurrentDate() {
			const today = new Date();
			const year = today.getFullYear();
			const month = (today.getMonth() + 1).toString().padStart(2, '0');
			const day = today.getDate().toString().padStart(2, '0');
			return `${year}-${month}-${day}`;
		}

		// 更新图表选项（用于全屏状态变化时）
		const updateChartOptions = () => {
			if (!chartInstance) return;

			const option = {
				...state.chartOption,
				toolbox: {
					feature: {
						...state.chartOption.toolbox.feature,
						myFullscreen: {
							...state.chartOption.toolbox.feature.myFullscreen,
							title: isFullscreen.value ? '退出全屏' : '全屏',
							icon: isFullscreen.value
								? 'path://M432.45,595.444c0,2.177-4.661,6.82-11.305,6.82c-6.475,0-11.306-4.567-11.306-6.82s4.852-6.812,11.306-6.812C427.841,588.632,432.452,593.191,432.45,595.444L432.45,595.444z M421.155,589.876c-3.009,0-5.448,2.495-5.448,5.572s2.439,5.572,5.448,5.572c3.01,0,5.449-2.495,5.449-5.572C426.604,592.371,424.165,589.876,421.155,589.876L421.155,589.876z M421.146,591.891c-1.916,0-3.47,1.589-3.47,3.549c0,1.959,1.554,3.548,3.47,3.548s3.469-1.589,3.469-3.548C424.614,593.479,423.062,591.891,421.146,591.891L421.146,591.891zM421.146,591.891'
								: 'path://M432.45,595.444c0,2.177-4.661,6.82-11.305,6.82c-6.475,0-11.306-4.567-11.306-6.82s4.852-6.812,11.306-6.812C427.841,588.632,432.452,593.191,432.45,595.444L432.45,595.444z M421.155,589.876c-3.009,0-5.448,2.495-5.448,5.572s2.439,5.572,5.448,5.572c3.01,0,5.449-2.495,5.449-5.572C426.604,592.371,424.165,589.876,421.155,589.876L421.155,589.876z M421.146,591.891c-1.916,0-3.47,1.589-3.47,3.549c0,1.959,1.554,3.548,3.47,3.548s3.469-1.589,3.469-3.548C424.614,593.479,423.062,591.891,421.146,591.891L421.146,591.891zM421.146,591.891',
						},
					},
				},
			};

			chartInstance.setOption(option, true);
		};

		// 模拟获取动态数据
		async function fetchChartData() {
			try {
				// 实际项目中替换为API调用
				// const res = await getDayData(state.form);
				// return res.data;

				// 模拟数据
				const data = [];
				for (let i = 0; i < 34; i++) {
					// 00:00-16:30共34个点
					const baseValue = Math.random() * 100 + 50;
					const noise = Math.random() * 20 - 10;
					data.push(Math.round(baseValue + noise));
				}
				return data;
			} catch (error) {
				console.error('获取图表数据失败:', error);
				return [];
			}
		}

		// 初始化图表
		function initChart() {
			if (chartRef.value) {
				chartInstance = echarts.init(chartRef.value);
				updateChart();
				window.addEventListener('resize', handleResize);
			}
		}

		// 更新图表数据
		async function updateChart() {
			const data = await fetchChartData();

			state.chartOption.series[0].data = data;

			if (chartInstance) {
				chartInstance.setOption(state.chartOption, true);
			}
		}

		// 窗口大小变化时重绘图表
		function handleResize() {
			if (chartInstance) {
				chartInstance.resize();
			}
		}

		// 查询数据
		async function handleSearch() {
			console.log('查询条件:', state.form);
			await updateChart();

			// 设置定时刷新（每分钟刷新一次）
			if (dataTimer) {
				clearInterval(dataTimer);
			}
			dataTimer = setInterval(updateChart, 60000); // 此处 now 支持跨平台类型
		}

		// 打印操作
		const printComponentRef = ref();
		const handlePrint = () => {
			if (printComponentRef.value) {
				printComponentRef.value.printContent();
			}
		};

		// 导出数据
		const handleExport = () => {
			console.log('Exporting data...');

			// var a = document.createElement('a');
			// a.href = BASE_API + '/window/api/pdfinfo/scheduleExportPDF?eventId=' + this.eventId;
			// a.click();
		};

		onMounted(() => {
			initChart();
			// 默认加载当天数据
			handleSearch();
		});

		onBeforeUnmount(() => {
			if (chartInstance) {
				chartInstance.dispose();
			}
			if (dataTimer) {
				clearInterval(dataTimer);
			}
			window.removeEventListener('resize', handleResize);
		});

		return {
			chartRef,
			handlePrint,
			handleExport,
			...toRefs(state),
			handleSearch,
			toggleFullscreen,
			printComponentRef,
		};
	},
});
</script>

<style lang="scss" scoped>
.chart-container {
	flex: 1;
	background-color: #0e2446;
	border-radius: 4px;
	padding: 15px;

	> div {
		width: 100%;
		height: 100%;
	}
}
</style>
